<template>
  <div class="app-container">
    <div style="font-size: medium; font-weight: bold;">被我代理的用户</div>
    <el-table v-loading="loading" :data="dataProxyTargetList">
      <el-table-column label="被代理人姓名" prop="proxyTargetName" align="center" :show-overflow-tooltip="true" min-width="100"/>
      <el-table-column label="被代理人ID" prop="proxyTargetId" align="center" :show-overflow-tooltip="true" min-width="100"/>
      <el-table-column label="流程分类" prop="wfCategory" align="center" :show-overflow-tooltip="true" min-width="100">
      <template #default="scope">
        <div v-if="scope.row.wfCategory === '' || scope.row.wfCategory === null">全部分类</div>
        <div v-else>{{scope.row.wfCategory}}</div>
      </template>
      </el-table-column>
      <el-table-column label="流程编码" prop="wfCode" align="center" :show-overflow-tooltip="true" min-width="100">
        <template #default="scope">
          <div v-if="scope.row.wfCode === '' || scope.row.wfCode === null">分类下全部流程</div>
          <div v-else>{{scope.row.wfCode}}</div>
        </template>
      </el-table-column>
      <el-table-column label="启用" prop="enable" align="center" :show-overflow-tooltip="true" min-width="100">
        <template #default="scope">
          <div v-if="scope.row.enable === 'Y'"><el-tag type="success">是</el-tag> </div>
          <div v-if="scope.row.enable === 'N'"><el-tag type="danger">否</el-tag> </div>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" prop="effectiveTime" align="center" width="160"/>
      <el-table-column label="失效时间" prop="failureTime" align="center" width="160"/>
    </el-table>
    <pagination v-show="proxyTargetTotal>0" :total="proxyTargetTotal" v-model:page="queryProxyTargetParams.pageNum" v-model:limit="queryProxyTargetParams.pageSize" @pagination="getProxyTargetList" />


    <div style="font-size: medium; font-weight: bold; margin-top: 100px">代理我的用户
      <text-add-button @click="handleAdd" />
    </div>
    <el-table v-loading="loading" :data="dataProxyList">
      <el-table-column label="代理人姓名" prop="proxyName" align="center" :show-overflow-tooltip="true" min-width="100"/>
      <el-table-column label="代理人ID" prop="proxyId" align="center" :show-overflow-tooltip="true" min-width="100"/>
      <el-table-column label="流程分类" prop="wfCategory" align="center" :show-overflow-tooltip="true" min-width="100">
        <template #default="scope">
          <div v-if="scope.row.wfCategory === '' || scope.row.wfCategory === null">全部分类</div>
          <div v-else>{{scope.row.wfCategory}}</div>
        </template>
      </el-table-column>
      <el-table-column label="流程编码" prop="wfCode" align="center" :show-overflow-tooltip="true" min-width="100">
        <template #default="scope">
          <div v-if="scope.row.wfCode === '' || scope.row.wfCode === null">分类下全部流程</div>
          <div v-else>{{scope.row.wfCode}}</div>
        </template>
      </el-table-column>
      <el-table-column label="启用" prop="enable" align="center" :show-overflow-tooltip="true" min-width="100">
        <template #default="scope">
          <div v-if="scope.row.enable === 'Y'"><el-tag type="success">是</el-tag> </div>
          <div v-else><el-tag type="danger">否</el-tag> </div>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" prop="effectiveTime" align="center" width="160"/>
      <el-table-column label="失效时间" prop="failureTime" align="center" width="160"/>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <text-edit-button @click="handleUpdate(scope.row)" />
          <text-delete-button @click="handleDelete(scope.row)"
                              :title="'是否确认删除代理人【'+scope.row.proxyName+'】?'" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="proxyTotal>0" :total="proxyTotal" v-model:page="queryProxyParams.pageNum" v-model:limit="queryProxyParams.pageSize" @pagination="getProxyList" />


    <!-- 新增或修改对话框 -->
    <el-dialog drag-dialog :title="editForm.title" :close-on-click-modal="false" v-model="editForm.open" width="800px" append-to-body>
      <el-form ref="formRef" :model="editForm.data" :rules="editForm.rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="选择代理人" prop="proxyName">
              <div class="input-and-button">
                <el-input
                  placeholder="请选择代理人"
                  v-model="editForm.data.proxyName"
                  :disabled="true">
                </el-input>
                <add-button text="选择" @click="handleAddProxy" />
              </div>
              <org-picker ref="orgPicker" title="选择代理人" @ok="handleSelectUser"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="授权代理分类" prop="wfCategory">
              <el-tree-select
                v-model="editForm.data.wfCategory" :data="formatCateOptions" check-strictly :render-after-expand="false"
                multiple check-on-click-node show-checkbox placeholder="请选择流程所属分类" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="授权代理流程" prop="wfCode">
              <el-select
                v-model="editForm.data.wfCode"
                multiple
                filterable
                clearable
                :loading="loading"
                placeholder="请选择流程"
              >
                <el-option
                  v-for="item in deploymentList"
                  :key="item.key"
                  :label="item.name+'('+item.key+')'"
                  :value="item.key"
                />
              </el-select>
              <div style="color: red">授权分类和授权流程同时选择时，取并集；都不选表示所有流程</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="是否启用" prop="enable">
              <el-switch
                v-model="editForm.data.enable"
                active-text="启用"
                active-value="Y"
                inactive-value="N"
                inactive-text="禁用">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="生效时间" prop="effectiveTime">
              <el-date-picker
                v-model="editForm.data.effectiveTime"
                type="datetime"
                placeholder="选择生效时间"
                :shortcuts="shortcuts"
                value-format="YYYY-MM-DD HH:mm:ss"
                align="right">
              </el-date-picker>
              <div style="color: red">生效时间为空表示立即生效</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="失效时间" prop="failureTime">
              <el-date-picker
                v-model="editForm.data.failureTime"
                type="datetime"
                placeholder="选择失效时间"
                :shortcuts="shortcuts"
                value-format="YYYY-MM-DD HH:mm:ss"
                align="right">
              </el-date-picker>
              <div style="color: red">失效时间为空表示永久生效</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <dialog-footer @ok="submitForm" @cancel="cancel" />
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script>
import { insert, deleteById, updateById, selectById } from "@wf/api/wf/task/proxySetting";
import {search as searchWf } from "@wf/api/wf/deployment";
import { debounceWrapper } from '@/utils/zmids';
import {searchProxyTargetUser, searchProxyUser} from "@/platform/wf/api/wf/task/proxySetting.js";
import OrgPicker from "@/components/Zmids/OrgPicker/index.vue";
import TextAddButton from "@/components/Zmids/Buttons/TextAddButton.vue";
import {getCategoryTree} from '@uni/api/uni/category/info';
import TextEditButton from "@/components/Zmids/Buttons/TextEditButton.vue";
import TextDeleteButton from "@/components/Zmids/Buttons/TextDeleteButton.vue";
import AddButton from "@/components/Zmids/Buttons/AddButton.vue";

export default {
  // 此处的名字需要与菜单中Path一致，否则多Tab页切换时会刷新
  name: 'WfProxySetting',
  components: {AddButton, TextDeleteButton, TextEditButton, TextAddButton, OrgPicker},
  data() {
    return {
      // 遮罩层
      loading: false,
      shortcuts: [
        {
          text: '现在',
          value: new Date(),
        },
        {
          text: '一天后',
          value: () => {
            const date = new Date()
            date.setDate(date.getDate() + 1)
            return date
          },
        },
        {
          text: '三天后',
          value: () => {
            const date = new Date()
            date.setDate(date.getDate() + 3)
            return date
          },
        },
        {
          text: '一周后',
          value: () => {
            const date = new Date()
            date.setDate(date.getDate() + 7)
            return date
          },
        },
      ],
      // 格式流程分类树选项
      formatCateOptions: undefined,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      proxyTargetTotal: 0,
      proxyTotal: 0,
      // 被代理用户表格数据
      dataProxyTargetList: [],
      // 代理我的用户表格数据
      dataProxyList: [],
      // 表单参数
      form: {
        id: undefined,
        name: '',
        key: '',
        sequenceCode: '',
        enableAuth: '',
        catecode: '',
        category: ''
      },
      // 查询参数
      queryProxyTargetParams: {
        pageNum: 1,
        pageSize: 10,
      },
      queryProxyParams: {
        pageNum: 1,
        pageSize: 10,
      },
      editForm: {
        // 控制 dialog
        open: false,
        // 弹出层标题
        title: '',
        // 是否修改操作
        isModify: false,
        // 表单参数
        data: {
          // 主键ID
          id: undefined,
          // 代理人姓名
          proxyName: '',
          // 代理人ID
          proxyId: undefined,
          // 被代理人姓名
          proxyTargetName: '',
          // 被代理人ID
          proxyTargetId: undefined,
          // 流程编码
          wfCode: '',
          // 流程分类
          wfCategory: '',
          // 是否启用[Y:启用，N:禁用]
          enable: 'Y',
          // 生效时间
          effectiveTime: undefined,
          // 失效时间
          failureTime: undefined,
          // 创建时间
          createTime: undefined,
          // 创建人
          createBy: '',
          // 修改时间
          updateTime: undefined,
          // 修改人
          updateBy: '',
        },
        // 规则
        rules: {
          // 代理人ID
          proxyId: [
            { required: true, message: '代理人ID不可以为空', trigger: 'blur' }
          ],
          // 被代理人ID
          proxyTargetId: [
            { required: true, message: '被代理人ID不可以为空', trigger: 'blur' }
          ],
          // 流程编码
          wfCode: [],
          // 生效时间与失效时间校验，失效时间不能在生效时间之前
          effectiveTime: [
            // 失效时间不能在生效时间之前
              {  trigger: 'blur', validator: (rule, value, callback) => {
                if (value && this.editForm.data.failureTime && value > this.editForm.data.failureTime) {
                  callback(new Error('生效时间不能在失效时间之后'));
                } else {
                  callback();
                }
              } }
          ],
          failureTime: [
              // 失效时间不能在生效时间之前
              {  trigger: 'blur', validator: (rule, value, callback) => {
                if (value && value < this.editForm.data.effectiveTime) {
                  callback(new Error('失效时间不能在生效时间之前'));
                } else {
                  callback();
                }
              } }
          ],


        },
      },
      // 查询流程部署参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10
      },
      deploymentList: [],
      deploymentTotal: 0,
    };
  },
  created() {
    // 查询被代理人列表
    this.getProxyTargetList();
    // 查询代理人列表
    this.getProxyList();
    // 查询流程分类
    this.getTreeselect();
    // 查询流程
    this.getWfOptions();

  },
  methods: {
    /** 查询下拉树结构 */
    getTreeselect: debounceWrapper(function () {
      getCategoryTree('anvil_wf_platform').then((response) => {
        this.cateOptions = response.data;
        this.formatCateOptions = this.formatCate(this.cateOptions);
      })
    }),
    formatCate(options) {
      return options.map(option => ({
        value: option.params.cateCode,  // 使用 params.cateCode 作为 value
        label: option.name,             // 使用 name 作为 label
        children: option.children ? this.formatCate(option.children) : []  // 递归处理 children
      }));
    },

    getWfOptions(){
      searchWf(this.queryParams).then((response) => {
        this.deploymentList = response.data.list
        this.deploymentTotal = response.data.total
      })
    },

    // 查询被代理用户列表
    getProxyTargetList: debounceWrapper(function () {
      this.loading = true;
      searchProxyTargetUser(this.queryProxyTargetParams).then(
          response => {
            this.dataProxyTargetList = response.data.list;
            this.proxyTargetTotal = response.data.total;
            this.loading = false;
          }
      );
    }),
    // 查询代理用户列表
    getProxyList: debounceWrapper(function () {
      this.loading = true;
      searchProxyUser(this.queryProxyParams).then(
          response => {
            this.dataProxyList = response.data.list;
            this.proxyTotal = response.data.total;
            this.loading = false;
          }
      );
    }),
    // 表单重置
    reset() {
      this.editForm.isModify = false;
      this.editForm.data = {
        // 主键ID
        id: undefined,
        // 代理人姓名
        proxyName: '',
        // 代理人ID
        proxyId: undefined,
        // 被代理人姓名
        proxyTargetName: '',
        // 被代理人ID
        proxyTargetId: undefined,
        // 流程编码
        wfCode: '',
        // 流程分类
        wfCategory: '',
        // 是否启用[Y:启用，N:禁用]
        enable: 'Y',
        // 生效时间
        effectiveTime: undefined,
        // 失效时间
        failureTime: undefined,
        // 创建时间
        createTime: undefined,
        // 创建人
        createBy: '',
        // 修改时间
        updateTime: undefined,
        // 修改人
        updateBy: '',
      };
      // 重置字段校验
      this.$refs.formRef && this.$refs.formRef.clearValidate();
      this.resetForm("formRef");
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.editForm.open = true;
      this.editForm.isModify = false;
      this.editForm.title = "新增";
    },
    // 删除按钮操作
    handleDelete: debounceWrapper(function (row) {
      const deleteIds = row ? row.id : this.ids.join(",");
      deleteById(deleteIds)
          .then(() => {
            this.getProxyList();
            this.msgSuccess("删除成功");
          }).catch(function () { });
    }),
    // 修改按钮操作
    handleUpdate: debounceWrapper(function (row) {
      this.reset();
      selectById(row.id).then(response => {
        this.editForm.data = response.data;
        this.editForm.data.wfCode = this.editForm.data.wfCode != null ? this.editForm.data.wfCode.split(',') : null;
        this.editForm.data.wfCategory = this.editForm.data.wfCategory != null ? this.editForm.data.wfCategory.split(',') : null;
        this.editForm.open = true;
        this.editForm.isModify = true;
        this.editForm.title = "修改";
      });

    }),
    // 提交按钮
    submitForm: debounceWrapper(function () {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          if (this.editForm.data.wfCode !== null && this.editForm.data.wfCode !== undefined
              && this.editForm.data.wfCode !== '' && Array.isArray(this.editForm.data.wfCode) ){
            this.editForm.data.wfCode = this.editForm.data.wfCode.join(',');
          }
          if (this.editForm.data.wfCategory !== null && this.editForm.data.wfCategory !== undefined
              && this.editForm.data.wfCategory !== '' && Array.isArray(this.editForm.data.wfCategory)) {
            this.editForm.data.wfCategory = this.editForm.data.wfCategory.join(',')
          }

          const ifUpdate = this.editForm.isModify;
          const promise = ifUpdate ? updateById(this.editForm.data) : insert(this.editForm.data);
          promise.then(response => {
            if (response.code === "200") {
              this.msgSuccess(ifUpdate ? '修改成功' : '新增成功');
              this.editForm.open = false;
              this.getProxyTargetList();
              this.getProxyList();
            }
          });
        }
      });
    }),
    // 取消按钮
    cancel() {
      this.editForm.open = false;
      this.reset();
    },

    // 选择人员
    handleAddProxy(){
      this.$refs.orgPicker.show()
    },
    handleSelectUser(users){
      this.editForm.data.proxyId = users
          .map((user) => {
            return user.userId;
          })
          .join(',');
      this.editForm.data.proxyName = users
          .map((user) => {
            return user.userName;
          })
          .join(',');
    }
  },
}
</script>

<style lang="scss" scoped>
/* 在 CSS 中添加样式 */
.input-and-button {
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中对齐 */
}

</style>
